<template>
    <div class="dashboard">
        <div class="header main-color">
            <h5>Locker Expert 数据分析平台</h5>
            <router-link class="main-color" :to="{path:'/Login'}">
                注销
            </router-link>
            <span class="time">{{time}}</span>
        </div>
        <div class="main-color vune-title">{{client[indexCarousel].name}}</div>
        <div class="map">
            <div id="myChartChina" :style="{width:'60%',height: '450px'}"></div>
            <div id="chartCity" :style="{width:'40%',height: '450px'}"></div>
        </div>
        <!-- <button @click="test(2)">change</button> -->
        <el-carousel :interval="5000" indicator-position='none' @change="carouselChange" height="1500px">
            <el-carousel-item v-for="(item,j) in client" :key="item.name">
                <div class="average-layout" ref="child">
                    <div class="data">
                        <!-- <div class="main-color vune-title">{{item.name}}</div> -->
                        <div class="card-left" v-for="n in groups[j]" :key="n.name">
                            <div class="card-detail">
                                <div><i class="el-icon-baseball"></i> 店名：{{n.name}}</div>
                                <label>地址：{{n.address}}</label>
                                <!-- <label>更新时间：{{n.updateTime}}</label> -->
                                <!-- <label>创建时间：{{n.createTime}}</label> -->
                                <label>联系方式：{{n.phone}}</label>
                            </div>
                            <div class="card">
                                <div class="card-title">
                                    {{n.name}}
                                </div>
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th v-for="i in ['组别','使用中','剩余']" :key="i">{{i}}</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr v-for="i in n.groups" :key="i.name">
                                            <td>{{i.name}}</td>
                                            <td class="used-color">{{i.useNum}}个</td>
                                            <td class="left-color">{{i.surplusNum}}个</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="chart">
                        <div :id="'mainUser'+j" class="chart-item" style="min-height:350px"></div>
                        <div :id="'mainBar'+j" class="chart-item"></div>
                    </div>
                </div>
            </el-carousel-item>
        </el-carousel>
    </div>
</template>
<script>
var Stomp = require('stompjs');
import china from 'echarts/map/json/china.json';
import { anhui, aomen, beijing, chongqing, fujian, gansu, guangdong, guangxi, guizhou, hainan, hebei, heilongjiang, 
henan, hubei, hunan, jiangsu, jiangxi, jilin, liaoning, neimenggu, ningxia, qinghai, shandong, shanghai,shanxi, 
sichuan, taiwan, tianjin, xianggang, xinjiang, xizang, yunnan,zhejiang } from './index.js';
echarts.registerMap('china', china);
export default {
    data(){
        return {
            // baseUrl:'ws://192.168.31.120:15674/ws',//本地
            // backSocketUrl:'http://192.168.31.120:15674/stomp',
            baseUrl:'wss://47.104.244.164:15674/ws',//服务器
            backSocketUrl:'https://47.104.244.164:15674/stomp',
            client:JSON.parse(sessionStorage.getItem('user')),
            groups:[],
            chartArr:[],
            chartBarArr:[],
            myChart:[],
            myBarChart:[],
            indexCarousel:0,
            chartChina:'',
            chartCity:'',
            count:0
        }
    },
    beforeCreate(){
    },
    created(){
        try{
            this.getData();
        }catch(e){
            console.log(e)
            this.$notify.error({title: '错误',message:e||'获取场馆信息失败！'});
        }
    },
    mounted(){
        // this.initConnect();
        this.drawLine();
    },
    computed:{
        time(){
            return moment().format('YYYY-MM-DD HH:mm');
        },
        total(){
            return this.chartArr.map(t=>(~~t.usedNum+~~t.leftNum));
        }
    },
    methods:{
        initConnect(){
            if (typeof WebSocket == 'undefined') {
                console.log('不支持websocket')
                var ws = new SockJS(this.backSocketUrl);
            }else{
                // 初始化 ws 对象
                var ws = new WebSocket(this.baseUrl);
            }
            // 获得Stomp client对象
            this.clientSocket = Stomp.over(ws);

            // SockJS 不支持 heart-beat
            this.clientSocket.heartbeat.outgoing = 60000;
            this.clientSocket.heartbeat.incoming = 60000;
            this.clientSocket.connect('ymty', 'ymty', this.connect, this.error, '/ymty');
        },
        connect(){
            this.count = 0;
            //data.body是接收到的数据
            this.clientSocket.subscribe("/exchange/YMTY-VIEW-EXCHANGE", (data)=> {
                var key;
                this.client.forEach((t,i)=>{
                    if(t.id==data.body){
                        key = i;
                        return;
                    }
                });
                try{
                    setTimeout(()=>{
                        this.getData(key);
                    },1000);
                }catch(e){
                    console.log(e)
                    this.$notify.error({title: '错误',message:e||'获取场馆信息失败！'});
                }
            },{ "x-message-ttl": 2000 });
        },
        error(error){
            // 超过20次连接失败，将不再请求连接。
            if(++this.count<=19){
                this.initConnect();
            }
        },
        async getData(key='none'){
            var clientArr,that = this;
            if(key!=='none'){
                clientArr = this.client.slice(key,key+1);
            }else{
                clientArr = this.client;
            }
            var PromiseArr = [];
            for(let i=0;i<clientArr.length;i++){
                PromiseArr[i] = axios.post(`store/group`,{'clientId':clientArr[i].id});
            }
            let data = await Promise.all(PromiseArr);
            if(key!=='none'){//修改单个数据
                var item = data.map(({data})=>{return data})[0];
                this.$set(this.groups,key,item);
                var chartItem = chartItemFun(item);
                this.$set(this.chartArr,key,chartItem);
                this.$set(this.chartBarArr,key,barChartFun(item));
                this.getChart(key);
                this.getBarChart(key);
            }else{//加载全部
                this.groups = data.map(({data})=>{return data});
                this.chartArr=this.groups.map((t,j)=>{
                    return chartItemFun(t);
                });
                this.chartBarArr = this.groups.map((t,j)=>{
                    return barChartFun(t);
                });
                this.getChart();
                this.getBarChart();
            }
            function chartItemFun(t){//处理饼状图数据
                if(t.length==0){
                    return {'usedNum':0,'leftNum':0};
                }
                let res = t.map(({groups},k)=>{
                    if(groups.length==1){
                        return {'useNum':groups[0].useNum,'surplusNum':groups[0].surplusNum};
                    }else{
                        var useNum = groups.map(t=>t.useNum).reduce((a,b)=>a+b);
                        var surplusNum = groups.map(t=>t.surplusNum).reduce((a,b)=>a+b);
                        return {useNum,surplusNum};
                    }
                });
                if(res.length==1){
                    return {'usedNum':res[0].useNum,'leftNum':res[0].surplusNum};
                }
                var usedNum = res.map(t=>t.useNum).reduce((a,b)=>a+b);
                var leftNum = res.map(t=>t.surplusNum).reduce((a,b)=>a+b);
                return {usedNum,leftNum};
            }
            function barChartFun(t){//处理柱状图数据
                if(t.length==0){
                    return;
                }
                let item={name:'',useNum:0,surplusNum:0};
                ['name','useNum','surplusNum'].forEach(element => {
                    item[element] = t.map((e)=>{
                        return e.groups.map((barI)=>{
                            if(element=='name'){
                                return e.name+barI[element];
                            }
                            return barI[element];
                        });
                    }).join().split(',');
                });
                return item;
            }
        },
        getChart(key='none'){//画饼状图
            var arr = this.chartArr;
            var that = this;
            if(key!=='none'){
                var option = optionFun(arr[key],key);
                this.myChart[key].setOption(option,true);
            }else{
                for(let i=0;i<arr.length;i++){
                    this.myChart[i] = echarts.init(document.getElementById('mainUser'+i), 'helianthus');
                    var option = optionFun(arr[i],i);
                    this.myChart[i].setOption(option,true);
                    $(window).resize(()=> {
                        this.myChart[i].resize();
                    });
                    $("#mainUser"+i).resize(()=> {
                        $(this.myChart[i]).resize();
                    });
                }
            }
            function optionFun(item,n){
                var re= {
                    backgroundColor: '#0f1422',
                    title: {
                        text: `${that.client[n].name}箱柜使用率`,
                        left: 'center',
                        top: 20,
                        textStyle: {
                            // color: 'aqua',
                            color: '#71c0e4',
                            fontWeight:500
                        }
                    },
                    legend: {
                        orient: 'vertical',
                        right: '5%',
                        top:'2%',
                        data: ['使用中','剩余'],
                        textStyle: {
                            fontSize: 12,
                            color: '#F1F1F3'
                        }
                    },
                    tooltip : {
                        trigger: 'item',
                        formatter: "{a} <br/>{b} : {c}个 ({d}%)"
                    },
                    series : [
                        {
                            name:'使用率',
                            type:'pie',
                            radius : '70%',
                            label:{
                                normal:{
                                    formatter:"{b} : {c}个 ({d}%)",
                                    textStyle: {
                                        fontWeight:600,
                                        fontSize:13                                
                                    }
                                },
                            },
                            center: ['50%', '55%'],
                            data:[
                                {value:item.usedNum, name:'使用中'},
                                {value:item.leftNum, name:'剩余'}
                            ],
                            itemStyle: {
                                emphasis: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ],
                    color: ['rgba(237,125,49, 0.4)','rgba(33,173,184, 0.4)']
                    // color:['#a6642e','#0e8fa0']
                };
                return re;
            }
        },
        getBarChart(key='none'){//画柱状图
            var arr = this.chartBarArr;
            var that = this;
            if(key!=='none'){
                var option = optionFun(key);
                this.myBarChart[key].setOption(option,true);
            }else{
                for(let i=0;i<arr.length;i++){
                    this.myBarChart[i] = echarts.init(document.getElementById('mainBar'+i), 'helianthus');
                    var option = optionFun(i);
                    this.myBarChart[i].setOption(option,true);
                    $(window).resize(()=> {
                        this.myBarChart[i].resize();
                    });
                    $("#mainBar"+i).resize(()=> {
                        $(this.myBarChart[i]).resize();
                    });
                }
            }
            // console.log(arr,'arr');
            function optionFun(n){
                var re= {
                    backgroundColor: '#0f1422',
                    title: {
                        text: `${that.client[n].name}箱柜`,
                        left: 'center',
                        top: 20,
                        textStyle: {
                            // color: 'aqua',
                            color: '#71c0e4',
                            fontWeight:500
                        }
                    },
                    legend: {
                        right: '5%',
                        top:'2%',
                        orient: 'vertical',
                        data: ['使用中','剩余'],
                        textStyle: {
                            fontSize: 12,
                            color: '#F1F1F3'
                        }
                    },
                    grid: {
                        left: '3%',
                        right: '3%',
                        // bottom: '3%',
                        containLabel: true
                    },
                    tooltip : {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                        // formatter: "{a} <br/>{b} : {c}个 ({d}%)"
                    },
                    xAxis: [
                        {
                            type: 'category',
                            axisTick: {show: false},
                            data: arr[n]?(arr[n].name):[],
                            axisLine: {
                                lineStyle: {
                                    color: '#0e8fa0'
                                }
                            },
                            axisLabel:{
                                interval: 0,
                                rotate:30
                            }
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            name: '数量/个',
                            interval: 50,
                            axisLabel: {
                                formatter: '{value}'
                            },
                            axisLine: {
                                lineStyle: {
                                    color: '#0e8fa0'
                                }
                            },
                            splitLine: {
                                lineStyle: {
                                    color: 'rgba(33,173,184, 0.2)',
                                    type:'dashed'
                                }
                            }
                        }
                    ],
                    series : [
                        {
                            name:'使用中',
                            type:'bar',
                            data:arr[n]?arr[n].useNum.map(t=>~~t):[],
                            // data:[2],
                            itemStyle:{
                                normal:{
                                    color: 'rgba(237,125,49, 0.4)'
                                }
                            },
                            // barWidth: 40
                        },
                        {
                            name:'剩余',
                            type:'bar',
                            data:arr[n]?(arr[n].surplusNum):[],
                            // data:[9],
                            itemStyle:{
                                normal:{
                                    color: 'rgba(33,173,184, 0.4)'
                                }
                            },
                            // barWidth: 40
                        }
                    ],
                };
                // console.log(re,'chart')
                return re;
            }
        },
        carouselChange(index){//走马灯切换
            this.chartChina.dispatchAction({type: 'downplay',name:this.client[this.indexCarousel].address[0]});
            this.indexCarousel = index;
            var address = this.client[index].address;
            this.chartChina.dispatchAction({type: 'highlight',name:address[0]});
            // myChartChina.on('mouseover',(v) => {
            //     if(v.name != address[0]){
            //         //当检测到鼠标悬停事件，取消默认选中高亮和提示框
            //         myChartChina.dispatchAction({
            //             type: 'hideTip',
            //             name:address[0]
            //         });
            //         myChartChina.dispatchAction({
            //             type: 'downplay',
            //             name:address[0]
            //         });
            //         //提示框显示悬停的那块
            //         myChartChina.dispatchAction({
            //             type: 'showTip',
            //             name:v.name
            //         });
            //     }
            // });
            // myChartChina.on('mouseout',(v) => {
            //     myChartChina.dispatchAction({type: 'highlight',seriesIndex:0,name:address[0]});
            //     myChartChina.dispatchAction({type: 'showTip',seriesIndex:0,name: address[0]});
            // });
            this.showCity(address[0],address[1]);
        },
        drawLine(){//中国地图
            this.chartChina = echarts.init(document.getElementById('myChartChina')); 

            var optionMap = {  
                tooltip: {
                    triggerOn: 'none'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    data:['']
                },
                visualMap: {
                    min: 0,
                    max: 600,
                    left: '5%',
                    top: 'bottom',
                    text: ['高','低'],
                    calculable : true,
                    color:['rgb(7, 248, 194)','#012f2b'],
                },   
                selectedMode: 'single',
                geo: {
                    show: true,
                    map: 'china',
                    top:'25',
                    bottom:'25',
                    label: {
                        normal: {
                            show: false
                        },
                        emphasis: {
                            show: false,
                        }
                    },
                    roam: false,
                    itemStyle: {
                        normal: {
                            // areaColor: '#01215c',
                            // borderWidth: 5,//设置外层边框
                            // borderColor: '#305bc5',
                            shadowColor: '#00BCD4',
                            shadowBlur: 25
                        }
                    }
                },
                series : [                      
                    {
                        z:1,
                        type: 'map',
                        mapType: 'china',
                        top:'25',
                        bottom:'25',
                        itemStyle: {
                            normal:{
                                areaColor: ['#0f1422'],
                                // borderColor: '#3cd2d2',
                                borderColor: '#2da5b1',
                            },
                            emphasis:{
                                areaColor:'#15e4e4',
                                shadowOffsetX: 0,
                                shadowOffsetY: 0,
                                shadowBlur: 20,
                                borderWidth: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },
                        showLegendSymbol: true,
                        label: {
                            normal: {
                                textStyle: {
                                    // color: '#7e9e32',
                                    color: '#7bcce7'
                                },
                                show: true
                            },
                            emphasis: {
                                show: true
                            }
                        },
                        data:[]
                    }
                ]
            };
        
            this.chartChina.setOption(optionMap);
            window.onresize=()=>{
                this.chartChina.resize();
            }
            // this.chartChina.on('click', (params)=> {
            //     this.showCity(params.name);
            // });            
        },
        showCity(province,city){//画城市地图
            switch(province){
                case '安徽': echarts.registerMap(province, anhui);break;
                case '澳门': echarts.registerMap(province, aomen);break;
                case '北京': echarts.registerMap(province, beijing);break;
                case '重庆': echarts.registerMap(province, chongqing);break;
                case '福建': echarts.registerMap(province, fujian);break;
                case '甘肃': echarts.registerMap(province, gansu);break;
                case '广东': echarts.registerMap(province, guangdong);break;
                case '广西': echarts.registerMap(province, guangxi);break;
                case '贵州': echarts.registerMap(province, guizhou);break;
                case '海南': echarts.registerMap(province, hainan);break;
                case '河北': echarts.registerMap(province, hebei);break;
                case '黑龙江': echarts.registerMap(province, heilongjiang);break;
                case '湖北': echarts.registerMap(province, hubei);break;
                case '湖南': echarts.registerMap(province, hunan);break;
                case '江苏': echarts.registerMap(province, jiangsu);break;
                case '江西': echarts.registerMap(province, jiangxi);break;
                case '吉林': echarts.registerMap(province, jilin);break;
                case '辽宁': echarts.registerMap(province, liaoning);break;
                case '内蒙古': echarts.registerMap(province, neimenggu);break;
                case '宁夏': echarts.registerMap(province, ningxia);break;
                case '青海': echarts.registerMap(province, qinghai);break;
                case '山东': echarts.registerMap(province, shandong);break;
                case '上海': echarts.registerMap(province, shanghai);break;
                case '山西': echarts.registerMap(province, shanxi);break;
                case '四川': echarts.registerMap(province, sichuan);break;
                case '台湾': echarts.registerMap(province, taiwan);break;
                case '天津': echarts.registerMap(province, tianjin);break;
                case '香港': echarts.registerMap(province, xianggang);break;
                case '新疆': echarts.registerMap(province, xinjiang);break;
                case '西藏': echarts.registerMap(province, xizang);break;
                case '云南': echarts.registerMap(province, yunnan);break;
                case '浙江': echarts.registerMap(province, zhejiang);break;
            }
            this.chartCity = echarts.init(document.getElementById('chartCity'));
            this.chartCity.setOption({
                tooltip:{
                    triggerOn:  'mousemove|click',
                    formatter: "{a} <br/>{b} : {c}人"
                },
                geo: {
                    show: true,
                    map: province,
                    top:'25',
                    bottom:'25',
                    label: {
                        normal: {
                            show: false
                        },
                        emphasis: {
                            show: false,
                        }
                    },
                    roam: false,
                    itemStyle: {
                        normal: {
                            // areaColor: '#01215c',
                            // borderWidth: 5,//设置外层边框
                            // borderColor: '#305bc5',
                            shadowColor: '#00BCD4',
                            shadowBlur: 25
                        }
                    }
                },
                series: [
                    {
                        type: 'map',
                        name: '场馆总人数',
                        mapType: province,
                        top:'25',
                        bottom:'25',
                        itemStyle: {
                            normal:{
                                areaColor: ['#0f1422'],
                                // borderColor: '#3cd2d2',
                                borderColor: '#2da5b1'
                            },
                            emphasis:{
                                areaColor:'#15e4e4',
                                shadowOffsetX: 0,
                                shadowOffsetY: 0,
                                shadowBlur: 20,
                                borderWidth: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },
                        label: {
                            normal: {
                                textStyle: {
                                    // color: '#7e9e32'
                                    color: '#7bcce7'
                                },
                                show: true
                            },
                            emphasis: {
                                show: true
                            }
                        },
                        data: [
                            { name: city, value: this.total[this.indexCarousel]}
                        ]
                    }
                ]
            });
            window.onresize=()=>{
                this.chartCity.resize();
                this.chartChina.resize();
            }
            this.chartCity.dispatchAction({type: 'highlight',name:city});
        }
    }
}
</script>
<style scoped>
    .dashboard{
        background: #0f1422;
        position: absolute;
        top: 0;
        right: 0;
        left: 0;
        bottom: 0;
        /* margin: 0; */
        min-height: 2120px;
        min-width: 1424px;
    }
    .header{
        height: 60px;
        margin: 0 20px;
        border-bottom: 1px solid #192d5e;
        box-shadow: 0px 15px 10px -15px #00BCD4;
        font-weight: 500;
        text-align: center;
    }
    .header h5{
        font-size: 25px;
        line-height: 60px;
        display: inline-block;
    }
    .header .time, .header a{
        float: right;
        font-weight: 400;
        font-size: 13px;
        line-height: 90px;
        margin-left: 5px;
    }
    
    .average-layout{
        display: flex;
        justify-content:space-around;
        padding: 0 35px; 
        margin-top: 20px;
    }
    .data{
        /* border-right: 1px solid #192d5e; */
        width: 45%;
        padding: 15px;
        min-height: 500px;
        /* overflow-y: auto; */
    }
    .chart{
        width: 50%;
        padding: 15px;
    }
    .chart div:not(:last-child){
        margin-bottom: 40px;
    }
    .chart-item{
        box-shadow: 0 0 18px #00BCD4;
        position: relative; 
        overflow: hidden; 
        width:100%;
        min-height: 450px; 
        cursor: default;
        padding-top:15px;
        border: 1px solid #192d5e; 
        border-radius: 5px;
    }
    .card-detail{
        background-color: #0f1422;
        /* margin: 21px 0; */
        margin-bottom: 30px;  
        border: 1px solid #192d5e;
        border-radius: 5px;
        padding: 20px 30px;
        /* width: 500px; */
        color: #71c0e4;
        box-shadow: 0 0 18px #00BCD4;
    }
    .card-detail label{
        width: 50%;
        height: 30px;
    }
    .card-detail div{
        height: 20px;
        border-bottom: 1px solid #192d5e;
        padding: 0px 7px 36px;
        margin: 0 -13px;
        margin-bottom: 20px;
    }
    .card-detail div i{
        color: #3cd2d2;
        font-weight: 600;
    }
    .card{
        background-color: #0f1422;
        margin-top: 15px;
        margin-bottom: 40px;
        border: 1px solid #192d5e;
        border-radius: 5px;
        padding: 0 15px 20px 15px;
    }
    .el-text-danger{
        color: #F56C6C
    }
    .el-text-success{
        color: #67C23A;
    }
    .card-title{
        color: aqua;
        font-size: 17px;
        font-weight: 500;
        height: 40px;
        line-height: 40px;
        background-color: #19354c;
        margin: 0 -15px;
        padding: 0 15px;
    }
    .table{
        margin-top: 15px;
        color: #71c0e4;
        font-size: 13px;
    }
    .table thead th,.table td{
        border: 0px solid #71c0e4;
    }
    .table thead tr{
        background: #282b3d;
        
    }
    .table tr td,.table thead tr th{
        line-height: 20px;
        padding: 10px 12px;
    }
    .table thead tr th{
        font-weight: 500;
    }
    .table>tbody>tr:nth-of-type(even) {
        background-color: #23252f;
    }
    .used-color{
        color:#a6642e
    }
    .left-color{
        color:#5896b2
    }
    .main-color{
        /* color: #3cd2d2; */
        color: #7bcce7;
    }
    .vune-title{
        font-size: 20px;
        font-weight: 500;
        height: 30px;
        line-height: 60px;
        padding: 0 40px;
        letter-spacing: 1px;
    }
    .map{
        display: flex;
        justify-content:space-around;
    }
</style>
